package org.celery.modules.ticket.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import lombok.SneakyThrows;
import org.apache.commons.codec.Charsets;
import org.celery.modules.shop.entity.Shop;
import org.celery.modules.shop.service.IShopService;
import org.celery.modules.ticket.excel.CustomTicketExcel;
import org.celery.modules.ticket.excel.CustomTicketImportListener;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.excel.UserExcel;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.celery.modules.ticket.entity.CustomTicket;
import org.celery.modules.ticket.vo.CustomTicketVO;
import org.celery.modules.ticket.wrapper.CustomTicketWrapper;
import org.celery.modules.ticket.service.ICustomTicketService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单登记表 控制器
 *
 * @author Celery
 * @since 2023-09-23
 */
@RestController
@AllArgsConstructor
@RequestMapping("celery-custom-ticket/custom-ticket")
@Api(value = "订单登记表", tags = "订单登记表接口")
public class CustomTicketController extends BladeController {

	private final ICustomTicketService customTicketService;
	private final IShopService shopService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入customTicket")
	public R<CustomTicketVO> detail(CustomTicket customTicket) {
		CustomTicket detail = customTicketService.getOne(Condition.getQueryWrapper(customTicket));
		CustomTicketVO vo = CustomTicketWrapper.build().entityVO(detail);
		Shop shop = shopService.getShopById(vo.getShopId());
		if (Func.isNotEmpty(shop)) {
			vo.setShopName(shop.getResourceOwner());
		}
		return R.data(vo);
	}

	/**
	 * 分页 订单登记表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入customTicket")
	public R<IPage<CustomTicketVO>> list(CustomTicket customTicket, Query query,
										 @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime createTimeStart,
										 @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime createTimeEnd,
										 @RequestParam(required = false) String shopName,
										 @RequestParam(required = false) String tenantId,
										 @RequestParam(required = false) String ticketNumberLike,
										 BladeUser user) {
		QueryWrapper<CustomTicket> queryWrapper = Condition.getQueryWrapper(customTicket);
		if (Func.isNotEmpty(createTimeStart) && Func.isNotEmpty(createTimeEnd)) {
			queryWrapper.lambda().between(CustomTicket::getDate, createTimeStart, createTimeEnd);
		}
		if(!user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) || (!user.getRoleName().contains("administrator") && !user.getRoleName().contains("s_admin") && !user.getRoleName().contains("caiwu") && !user.getRoleName().contains("fake_boss"))) {
			List<Shop> shopList = shopService.authList(user);
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}

			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(CustomTicket::getShopId, shopIdList);
		}
		if (Func.isNotEmpty(shopName)) {
			List<Shop> shopList = shopService.list(Wrappers.<Shop>lambdaQuery().like(Shop::getResourceOwner, shopName));
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}
			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(CustomTicket::getShopId, shopIdList);
		}
		if (Func.isNotEmpty(ticketNumberLike)) {
			queryWrapper.lambda().like(CustomTicket::getTicketNumber, ticketNumberLike);
		}
		if (Func.isNotEmpty(tenantId)) {
			List<Shop> shopList = shopService.list(Wrappers.<Shop>lambdaQuery().eq(Shop::getTenantId, tenantId));
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}
			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(CustomTicket::getShopId, shopIdList);
		}
		IPage<CustomTicket> pages = customTicketService.page(Condition.getPage(query), queryWrapper);
		return R.data(CustomTicketWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 订单登记表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入customTicket")
	public R<IPage<CustomTicketVO>> page(CustomTicketVO customTicket, Query query) {
		IPage<CustomTicketVO> pages = customTicketService.selectCustomTicketPage(Condition.getPage(query), customTicket);
		return R.data(pages);
	}

	/**
	 * 新增 订单登记表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入customTicket")
	public R save(@Valid @RequestBody CustomTicket customTicket) {
		return R.status(customTicketService.save(customTicket));
	}

	/**
	 * 修改 订单登记表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入customTicket")
	public R update(@Valid @RequestBody CustomTicket customTicket) {
		return R.status(customTicketService.updateById(customTicket));
	}

	/**
	 * 新增或修改 订单登记表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入customTicket")
	public R submit(@Valid @RequestBody CustomTicket customTicket) {
		return R.status(customTicketService.saveOrUpdate(customTicket));
	}

	
	/**
	 * 删除 订单登记表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(customTicketService.deleteLogic(Func.toLongList(ids)));
	}

	@GetMapping("/statics")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取各店铺统计列表", notes = "无")
	public R<List<Map<String, Object>>> statics(@RequestParam(required = false) String shopName,
												@RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
												@RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
												@RequestParam(required = false) String tenantId,
												BladeUser user
	) {
		return R.data(customTicketService.staticsList(shopName, startTime, endTime, tenantId, user));
	}

	/**
	 * 导入统计信息
	 */
	@PostMapping("import-data")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导入统计信息", notes = "传入excel")
	public R importData(MultipartFile file, Integer isCovered) {
		String filename = file.getOriginalFilename();
		if (StringUtils.isEmpty(filename)) {
			throw new RuntimeException("请上传文件!");
		}
		if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
			throw new RuntimeException("请上传正确的excel文件!");
		}
		InputStream inputStream;
		try {
			CustomTicketImportListener importListener = new CustomTicketImportListener(customTicketService);
			inputStream = new BufferedInputStream(file.getInputStream());
			ExcelReaderBuilder builder = EasyExcel.read(inputStream, CustomTicketExcel.class, importListener);
			builder.doReadAll();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.success("操作成功");
	}

	/**
	 * 导出模板
	 */
	@SneakyThrows
	@GetMapping("export-template")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		String fileName = URLEncoder.encode("订单数据模板", Charsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), CustomTicketExcel.class).sheet("订单数据").doWrite(list);
	}


}
